<?php
declare (strict_types=1);

namespace app\utils;

use app\APIResponse;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Request;

class JwtUtils {
    private static string $tokenKey = "authorization";

    /**
     * 验证token并返回解码后的数据
     * @param string $token
     * @return object|null
     */
    public static function verifyToken(string $token): ?object {
        try {
            $key = config('jwt.secret');
            $decoded = JWT::decode($token, new Key($key, 'HS256'));

            // 验证token是否过期
            if ($decoded->exp < time()) {
                return null;
            }

            return $decoded;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * 从请求中获取token
     * @param Request $request
     * @return string|null
     */
    public static function getTokenFromRequest(Request $request): ?string {
        $header = $request->header();
        return $header[self::$tokenKey] ?? null;
    }

    /**
     * 从请求中获取用户ID
     * @param Request $request
     * @return int|null
     */
    public static function getUidFromRequest(Request $request): ?int {
        $token = self::getTokenFromRequest($request);
        if (empty($token)) {
            return null;
        }

        $decoded = self::verifyToken($token);
        return $decoded?->data->uid;
    }

    /**
     * 验证请求中的token
     * @param Request $request
     * @return bool
     */
    public static function validateRequest(Request $request): bool {
        $token = self::getTokenFromRequest($request);
        if (empty($token)) {
            return false;
        }
        return self::verifyToken($token) !== null;
    }
} 